package middleware

import (
	"github.com/gin-gonic/gin"
	"go-web-app-demo/common"
	"go-web-app-demo/pkg/jwt"
	"net/http"
)

const (
	UserIDKey = "userID"
)

func JWTAuthMiddleware(c *gin.Context) {

	ah := c.GetHeader("Authorization")

	if ah == "" {
		c.JSON(http.StatusBadRequest, common.NewFailed("需要登录"))
		c.Abort()
		return
	}

	token, err := jwt.ParseToken(ah)
	if err != nil {
		c.JSON(http.StatusBadRequest, common.NewFailed("无效token"))
		c.Abort()
		return
	}

	c.Set(UserIDKey, token.UserID)
	c.Next()
}
